package com.collect.senegal.zhiScene.zhiCheckIn;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextClock;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.collect.senegal.MyApplication;
import com.collect.senegal.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.lihang.ShadowLayout;
import com.collect.senegal.R;
import com.collect.senegal.zhiBase.BaseActivity;
import com.collect.senegal.zhiBean.zhiReceive.ZHIRCheckInOutEntity;
import com.collect.senegal.zhiBean.zhiReceive.ZHIRSysConfigEntity;
import com.collect.senegal.zhiBean.zhiReceive.ZHIRWifiEntity;
import com.collect.senegal.zhiBean.zhiSend.ZHISCheckInOutEntity;
import com.collect.senegal.zhiBean.zhiSend.ZHISendEntity;
import com.collect.senegal.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.senegal.zhiHelper.WifiAutoConnectManager;
import com.collect.senegal.zhiHelper.ZHICallLogHelper;
import com.collect.senegal.zhiHelper.ZHIMainProcessHelper;
import com.collect.senegal.zhiScene.zhiWidget.zhiCutdown.ZHITimerTextView;
import com.collect.senegal.zhiScene.zhiWidget.zhiDialog.ZHIDialogMessage;
import com.collect.senegal.zhiScene.zhiWidget.zhiDialog.ZHIOnDialogButtonListener;
import com.collect.senegal.zhiScene.zhiWidget.zhiNavigationBar.ZHINavigationBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_CHECK_IN_WIFI)
public class ZHICheckInWifiActivity extends BaseActivity<ZHICheckInPresenter> implements ZHICheckInContract.View {

    @BindView(R.id.navigationBar)
    ZHINavigationBar navigationBar;

    @BindView(R.id.tv_ci_waiting_cutdown)
    TextView tv_ci_waiting_cutdown;

    @BindView(R.id.tv_ci_check_state)
    ZHITimerTextView tv_ci_check_state;

    @BindView(R.id.sl_ci_check_state)
    ShadowLayout sl_ci_check_state;

    @BindView(R.id.tc_ci_cur_service_time)
    TextClock tc_ci_cur_service_time;


    /**
     * 处理信号量改变或者扫描结果改变的广播
     */
    private BroadcastReceiver mWifiSearchBroadcastReceiver;
    private IntentFilter mWifiSearchIntentFilter;
    private BroadcastReceiver mWifiConnectBroadcastReceiver;
    private IntentFilter mWifiConnectIntentFilter;
    private WifiAutoConnectManager mWifiAutoConnectManager;
    private List<ScanResult> mScanResultList = new ArrayList<>();
    private ScanWifiListAsyncTask mScanWifiListAsyncTask = null;
    private ArrayList<ZHIRWifiEntity> mWifiList = new ArrayList<>();
    private static final int MIN_MATCH_WIFI_COUNT = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_in;
    }

    @Override
    protected void initInjector() {
        mActivityComponent.inject(this);
    }

    @Override
    protected void initView() {
        try {
            tc_ci_cur_service_time.setFormat24Hour("yyyy-MM-dd EEEE aa HH:mm:ss");
            tc_ci_cur_service_time.setFormat12Hour("yyyy-MM-dd EEEE aa HH:mm:ss");

            navigationBar.showRight().setCenterText(MyApplication.getAppContext().getString(R.string.clock_in_out)).setRightImgage(R.drawable.ic_111).setBarClickListener(new ZHINavigationBar.OnNavigationBarClickListener() {
                @Override
                public void onNavigationBarLeftClick(View v) {
                    if (tv_ci_check_state.getText().toString().trim().equalsIgnoreCase(MyApplication.getAppContext().getString(R.string.clock_in))) {
                        ZHIDialogMessage.showDialog(
                                getActivity(),
                                MyApplication.getAppContext().getString(R.string.tips),
                                MyApplication.getAppContext().getString(R.string.are_you_sure_you_don_clock_in),
                                MyApplication.getAppContext().getString(R.string.later),
                                MyApplication.getAppContext().getString(R.string.clock_in),
                                tag -> {
                                    if (0 == tag) {
                                        toGoBack();
                                    } else if (1 == tag) {
                                        toClickCheckInOut();
                                    }
                                });
                        return;
                    }
                    toGoBack();
                }

                @Override
                public void onNavigationBarRightClick(View v) {
                    ZHICheckInReduce.mFromCheckInPage = true;
                    ZHIProjectRouter.toCheckInHistory();
                }
            });

            tv_ci_check_state.setOnClickListener(v -> {
                try {
                    toClickCheckInOut();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            //初始化wifi工具
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            mWifiAutoConnectManager = WifiAutoConnectManager.newInstance(wifiManager);
            initWifiSate();

            //查询状态
            getCheckState();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        cleanTimer();

        try {
            unregisterReceiver(mWifiSearchBroadcastReceiver);
            unregisterReceiver(mWifiConnectBroadcastReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }

        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            cleanTimer();

            registerReceiver(mWifiSearchBroadcastReceiver, mWifiSearchIntentFilter);
            registerReceiver(mWifiConnectBroadcastReceiver, mWifiConnectIntentFilter);

            //new Handler().postDelayed(this::scanWifiList, 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetErrorInfo(String apiName) {
        try {
            if (apiName.equalsIgnoreCase("checkInOut")) {
                resetCheckInUI();
                //查询状态
                getCheckState();
            } else if (apiName.equalsIgnoreCase("getCheckState")) {
                resetCheckInUI();
            } else if (apiName.equalsIgnoreCase("getCheckStateWhenCheckedCompleted")) {
                resetCheckInUI();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onGetCheckState(ZHIRCheckInOutEntity zhirCheckInOutEntity) {
        try {
            if (zhirCheckInOutEntity.isToCheckIn()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText(MyApplication.getAppContext().getString(R.string.clock_in));
                navigationBar.setCenterText(MyApplication.getAppContext().getString(R.string.clock_in));

            } else if (zhirCheckInOutEntity.isToCheckOut()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText(MyApplication.getAppContext().getString(R.string.clock_out));
                navigationBar.setCenterText(MyApplication.getAppContext().getString(R.string.clock_out));

            } else {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
                tv_ci_check_state.setText(MyApplication.getAppContext().getString(R.string.completed));
                navigationBar.setCenterText(MyApplication.getAppContext().getString(R.string.clock_in_out));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onGetCheckStateWhenCheckedCompleted(ZHIRCheckInOutEntity zhirCheckInOutEntity) {
        try {
            resetCheckInUI();

            if (zhirCheckInOutEntity.isToCheckIn()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText(MyApplication.getAppContext().getString(R.string.clock_in));
                navigationBar.setCenterText(MyApplication.getAppContext().getString(R.string.clock_in));
                return;

            } else if (zhirCheckInOutEntity.isToCheckOut()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText(MyApplication.getAppContext().getString(R.string.clock_out));
                navigationBar.setCenterText(MyApplication.getAppContext().getString(R.string.clock_out));

            } else {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
                tv_ci_check_state.setText(MyApplication.getAppContext().getString(R.string.completed));
                navigationBar.setCenterText(MyApplication.getAppContext().getString(R.string.clock_in_out));
            }

            ZHIProjectRouter.toCheckInHistoryForLogin();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCheckInOut() {
        //查询状态
        if (mPresenter != null) {
            mPresenter.getCheckStateWhenCheckedCompleted(getActivity(), new ZHISendEntity());
        }
    }

    @Override
    public void onGetCheckHistory(ArrayList<ZHIRCheckInOutEntity> zhirCheckInOutEntityArrayList) {

    }

    @Override
    public void onGetAppConfig(ZHIRSysConfigEntity zhirSysConfigEntity) {
        try {
            mWifiList = zhirSysConfigEntity.getWfList();

            if (mWifiList.size() == 0) {
                toCheckInOut();
                return;
            }

            if (mScanResultList != null) {
                int existCount = 0;
                for (int i = 0; i < mScanResultList.size(); i++) {
                    ScanResult scanResult = mScanResultList.get(i);
                    if (isExistSSID(scanResult.SSID, scanResult.BSSID)) {
                        existCount += 1;
                    }
                }
                if (existCount < MIN_MATCH_WIFI_COUNT) {
                    ZHIDialogMessage.showDialog(ZHICheckInWifiActivity.this, null, MyApplication.getAppContext().getString(R.string.you_are_not_near_the_check_in_location_and_cannot_check_in), true, tag -> {
                        resetCheckInUI();
                        //查询状态
                        getCheckState();
                    });
                    return;
                }
                toCheckInOut();
            } else {
                ZHIDialogMessage.showDialog(ZHICheckInWifiActivity.this, null, MyApplication.getAppContext().getString(R.string.you_are_not_near_the_check_in_location_and_cannot_check_in), true, tag -> {
                    resetCheckInUI();
                    //查询状态
                    getCheckState();
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void toGoBack() {
        tv_ci_check_state.stopRun();
        if (ZHICheckInReduce.mFromLoginSuccess) {
            ZHICheckInReduce.mFromLoginSuccess = false;
            handlerLoginResult();
        } else {
            finish();
        }
    }

    @SuppressLint("SetTextI18n")
    private void resetCheckInUI() {
        tv_ci_check_state.stopRun();
        tv_ci_check_state.setText(MyApplication.getAppContext().getText(R.string.start));
        sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
        tv_ci_waiting_cutdown.setVisibility(View.GONE);
    }

    private void getCheckState() {
        //查询状态
        if (mPresenter != null) {
            mPresenter.getCheckState(getActivity(), new ZHISendEntity());
        }
    }

    @SuppressLint("SetTextI18n")
    private void getCurWifiList() {
        tv_ci_check_state.setOnTimerCompleted(this::resetCheckInUI);
        tv_ci_waiting_cutdown.setVisibility(View.VISIBLE);
        sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
        tv_ci_check_state.beginRun();

        scanWifiList();
    }

    private void toCheckInOut() {
        try {
            if (mPresenter != null) {
                ZHISCheckInOutEntity zhisCheckInOutEntity = new ZHISCheckInOutEntity();
                zhisCheckInOutEntity.updateLocationInfo();
                mPresenter.checkInOut(getActivity(), zhisCheckInOutEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlerLoginResult() {
        try {
            if (ZHIMainProcessHelper.getInstance().getLoginEntity() != null) {
                //偷偷的上传通话记录
                if (ZHICallLogHelper.FLAG_OPEN) {
                    ZHICallLogHelper.getInstance().initAppUserIds(ZHIMainProcessHelper.getInstance().getLoginEntity().getUserId());
                }

                //人脸界面
                if (ZHIProjectConfigs.OPEN_FACE_DETECT) {
                    if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLiveFlag()) {
                        ZHIProjectRouter.toRegFaceV2();
                        return;
                    }
                }

                //客服界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isCustomerFlag()) {
                    //电召界面
                    if (ZHIMainProcessHelper.getInstance().getLoginEntity().isCustomerWhitelistFlag()) {
                        ZHIProjectRouter.toRecallV2();
                        return;
                    }

                    //客服界面
                    ZHIProjectRouter.toCustomerServiceV2();
                    return;
                }

                //客服组长界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isCustomerDGroupFlag()) {
                    //客服界面
                    ZHIProjectRouter.toCustomerServiceAdmin();
                    return;
                }

                //电销界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isDxFlag()) {
                    ZHIProjectRouter.toRootTelemarketing();
                    return;
                }

                //电核界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isDhFlag()) {
                    ZHIProjectRouter.toRootDs();
                    return;
                }

                //单人审核界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isWholeKefuFlag()) {
                    ZHIProjectRouter.toRootAuditer();
                    return;
                }

                //改钱包客服角色界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isCustomerChangeWalletFlag()) {
                    ZHIProjectRouter.toRootDsChangeWallet();
                    return;
                }

                //大组长催收界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isBigGroupFlag()) {
                    ZHIProjectRouter.toRootBigGroup();
                    return;
                }

                //催收界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isGroupFlag()) {
                    if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB1()) {
                        ZHIProjectRouter.toRootGroupB1();
                    } else if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB2()) {
                        ZHIProjectRouter.toRootGroupB2();
                    } else {
                        ZHIProjectRouter.toRootGroup();
                    }
                } else {
                    if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB1()) {
                        ZHIProjectRouter.toRootMemberB1();
                    } else if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB2()) {
                        ZHIProjectRouter.toRootMemberB2();
                    } else {
                        ZHIProjectRouter.toRootMember();
                    }
                }

            } else {
                ZHIProjectRouter.toRegLoginV2();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void cleanTimer() {
        try {
            tv_ci_check_state.stopRun();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void toClickCheckInOut() {
        try {
            if (tv_ci_check_state.getText().toString().trim().contains(MyApplication.getAppContext().getString(R.string.clock_in))) {
                ZHIDialogMessage.showDialog(
                        getActivity(),
                        MyApplication.getAppContext().getString(R.string.tips),
                        MyApplication.getAppContext().getString(R.string.are_you_sure_you_want_to_clock_in_for_work),
                        MyApplication.getAppContext().getString(R.string.cancel),
                        MyApplication.getAppContext().getString(R.string.confirm),
                        tag -> {
                            if (1 == tag) {
                                getCurWifiList();
                            }
                        });
                return;
            }
            if (tv_ci_check_state.getText().toString().trim().contains(MyApplication.getAppContext().getString(R.string.clock_out))) {
                ZHIDialogMessage.showDialog(
                        getActivity(),
                        MyApplication.getAppContext().getString(R.string.tips),
                        MyApplication.getAppContext().getString(R.string.are_you_sure_you_want_to_clock_out_for_work),
                        MyApplication.getAppContext().getString(R.string.cancel),
                        MyApplication.getAppContext().getString(R.string.confirm),
                        tag -> {
                            if (1 == tag) {
                                toCheckInOut();
                            }
                        });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initWifiSate() {
        //wifi 搜索结果接收广播
        mWifiSearchBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action != null && action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                    // 扫描结果改表
                    Log.d(TAG, "onReceive: 扫描结果改表");
                    mScanResultList = WifiAutoConnectManager.getScanResults();
                }
            }
        };

        mWifiSearchIntentFilter = new IntentFilter();
        mWifiSearchIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
//        mWifiSearchIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//        mWifiSearchIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

        //wifi 状态变化接收广播
        mWifiConnectBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.d("mWifiConnectReceiver", "action: " + action);
                if (action != null) {
                    if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                        int wifState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
                        if (wifState != WifiManager.WIFI_STATE_ENABLED) {
                            //Toast.makeText(WifiTestActivity.this, "没有wifi", Toast.LENGTH_SHORT).show();
                            ZHIDialogMessage.showDialog(ZHICheckInWifiActivity.this, "Error!", "Please turn on the WIFI switch!", true, new ZHIOnDialogButtonListener() {
                                @Override
                                public void onButtonItemClick(int tag) {
                                    ZHICheckInWifiActivity.this.startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
                                }
                            });
                        }
                    } else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
                        int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                        Log.e(TAG, "SUPPLICANT_CONNECTION_CHANGE_ACTION:" + linkWifiResult);
                        if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                            Log.e(TAG, "ERROR_AUTHENTICATING: 密码错误");
                        }
                    } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                        NetworkInfo.DetailedState state = ((NetworkInfo) Objects.requireNonNull(intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO))).getDetailedState();
                    }
                }
            }
        };

        mWifiConnectIntentFilter = new IntentFilter();
//        mWifiConnectIntentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);
//        mWifiConnectIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//        mWifiConnectIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    }

    private void scanWifiList() {
        if (mScanWifiListAsyncTask != null) {
            mScanWifiListAsyncTask.cancel(true);
            mScanWifiListAsyncTask = null;
        }
        mScanWifiListAsyncTask = new ScanWifiListAsyncTask();
        mScanWifiListAsyncTask.execute();
    }

    @SuppressLint("StaticFieldLeak")
    private class ScanWifiListAsyncTask extends AsyncTask<Void, Void, List<ScanResult>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<ScanResult> doInBackground(Void... params) {
            if (WifiAutoConnectManager.startStan()) {
                List<ScanResult> filterScanResultList = WifiAutoConnectManager.getScanResults();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return filterScanResultList;
            }
            return new ArrayList<>();
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        protected void onPostExecute(final List<ScanResult> result) {
            super.onPostExecute(result);
            try {
                mScanResultList = result;

                if (mPresenter != null) {
                    mPresenter.getAppConfig(ZHICheckInWifiActivity.this, new ZHISendEntity());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isExistSSID(String ssid, String bssid) {
        if (mWifiList != null) {
            for (int i = 0; i < mWifiList.size(); i++) {
                ZHIRWifiEntity ZHIRWifiEntity = mWifiList.get(i);
                boolean ssidExist = ZHIRWifiEntity.getSsid().equalsIgnoreCase(ssid);
                boolean bssidExist = ZHIRWifiEntity.getBssid().equalsIgnoreCase(bssid);
                if (ssidExist && bssidExist) {
                    Log.d(TAG, ssid + " is a exist SSID");
                    return true;
                }
            }
        }
        Log.d(TAG, ssid + " not exist");
        return false;
    }
}